package com.apptest.android.ui.home;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.apptest.android.core.bean.ArticleItemBean;
import com.apptest.android.core.bean.ArticleListBean;
import com.apptest.android.core.bean.BannerBean;
import com.apptest.android.core.network.ApiEngine;
import com.apptest.android.core.network.BaseObserver;
import java.util.List;

public class HomeViewModel extends ViewModel {

    private MutableLiveData<List<ArticleItemBean>> articleItemList;
    private MutableLiveData<List<BannerBean>> bannerList;
    private int currentPage;

    public HomeViewModel() {
        articleItemList = new MutableLiveData<>();
        bannerList = new MutableLiveData<>();
        currentPage=0;
        getTopArticles();
        getBanners();
    }

    public LiveData<List<ArticleItemBean>> getArticleItemList() {
        return articleItemList;
    }

    public LiveData<List<BannerBean>> getBannerList() {
        return bannerList;
    }

    public void updateArticleItemList(boolean refresh){
        if(refresh){
            currentPage = 0;
            getTopArticles();
        }
        else {
            currentPage++;
            getArticles();
        }
    }

    private void getTopArticles(){
        ApiEngine.getTopArticles(new BaseObserver<List<ArticleItemBean>>() {
            @Override
            public void onSuccess(List<ArticleItemBean> list) {
                articleItemList.setValue(list);
            }
        });
    }

    private void getArticles(){
        ApiEngine.getArticleListData(currentPage, new BaseObserver<ArticleListBean>() {
            @Override
            public void onSuccess(ArticleListBean articleListBean) {
                articleItemList.getValue().addAll(articleListBean.getDatas());
                articleItemList.setValue(articleItemList.getValue());
            }
        });
    }

    private void getBanners(){
        ApiEngine.getBannerData(new BaseObserver<List<BannerBean>>() {
            @Override
            public void onSuccess(List<BannerBean> list) {
                bannerList.setValue(list);
            }
        });
    }

}